package com.yj.springbootmiaosha.redisLock;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.data.redis.core.types.Expiration;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 使用redis 实现分布式锁
 *
 * AutoCloseable: 自动关闭
 */
@Slf4j
public class RedisLock implements AutoCloseable {

    private RedisTemplate redisTemplate;
    private String key;
    private String value;
    private Integer expireTime;

    public RedisLock(RedisTemplate redisTemplate,String key,Integer expireTime){
        this.redisTemplate = redisTemplate;
        this.key = key;
        this.value = UUID.randomUUID().toString();
        this.expireTime = expireTime;
    }

    // 加锁
    public boolean getLock(){
        RedisCallback<Boolean> redisCallback = connection -> {
            byte [] resource_key = redisTemplate.getKeySerializer().serialize(key);
            byte [] random_value = redisTemplate.getValueSerializer().serialize(value);
            Expiration expiration = Expiration.seconds(expireTime);
            RedisStringCommands.SetOption setOption = RedisStringCommands.SetOption.SET_IF_ABSENT;
            boolean result = connection.set(resource_key,random_value,expiration,setOption);
            return result;
        };
        boolean result = (boolean) redisTemplate.execute(redisCallback);
        return result;
    }

    // 解锁
    public boolean unLock(){
        String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        RedisScript<Boolean> redisScript = RedisScript.of(script,Boolean.class);
        List<String> keys = Arrays.asList(key);
        boolean result = (boolean) redisTemplate.execute(redisScript,keys,value);
        return result;
    }


    @Override
    public void close() throws Exception {
        boolean result = unLock();
        log.info("释放锁结果：{}",result);
    }
}
